/**
 * Created by chenguangpeng on 15-6-18.
 */
moment.locale('zh_cn', {
    months : '一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月'.split('_'),
    monthsShort : '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),
    weekdays : '星期日_星期一_星期二_星期三_星期四_星期五_星期六'.split('_'),
    weekdaysShort : '周日_周一_周二_周三_周四_周五_周六'.split('_'),
    weekdaysMin : '日_一_二_三_四_五_六'.split('_'),
    longDateFormat : {
        LT : 'Ah点mm',
        L : 'YYYY-MM-DD',
        LL : 'YYYY年MMMD日',
        LLL : 'YYYY年MMMD日LT',
        LLLL : 'YYYY年MMMD日ddddLT',
        l : 'YYYY-MM-DD',
        ll : 'YYYY年MMMD日',
        lll : 'YYYY年MMMD日LT',
        llll : 'YYYY年MMMD日ddddLT'
    },
    meridiem : function (hour, minute, isLower) {
        var hm = hour * 100 + minute;
        if (hm < 600) {
            return '凌晨';
        } else if (hm < 900) {
            return '早上';
        } else if (hm < 1130) {
            return '上午';
        } else if (hm < 1230) {
            return '中午';
        } else if (hm < 1800) {
            return '下午';
        } else {
            return '晚上';
        }
    },
    calendar : {
        sameDay : function () {
            return this.minutes() === 0 ? '[今天]Ah[点整]' : '[今天]LT';
        },
        nextDay : function () {
            return this.minutes() === 0 ? '[明天]Ah[点整]' : '[明天]LT';
        },
        lastDay : function () {
            return this.minutes() === 0 ? '[昨天]Ah[点整]' : '[昨天]LT';
        },
        nextWeek : function () {
            var startOfWeek, prefix;
            startOfWeek = moment().startOf('week');
            prefix = this.unix() - startOfWeek.unix() >= 7 * 24 * 3600 ? '[下]' : '[本]';
            return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
        },
        lastWeek : function () {
            var startOfWeek, prefix;
            startOfWeek = moment().startOf('week');
            prefix = this.unix() < startOfWeek.unix()  ? '[上]' : '[本]';
            return this.minutes() === 0 ? prefix + 'dddAh点整' : prefix + 'dddAh点mm';
        },
        sameElse : 'LL'
    },
    ordinal : function (number, period) {
        switch (period) {
            case 'd':
            case 'D':
            case 'DDD':
                return number + '日';
            case 'M':
                return number + '月';
            case 'w':
            case 'W':
                return number + '周';
            default:
                return number;
        }
    },
    relativeTime : {
        future : '%s内',
        past : '%s前',
        s : '几秒',
        m : '1分钟',
        mm : '%d分钟',
        h : '1小时',
        hh : '%d小时',
        d : '1天',
        dd : '%d天',
        M : '1个月',
        MM : '%d个月',
        y : '1年',
        yy : '%d年'
    },
    week : {
        // GB/T 7408-1994《数据元和交换格式·信息交换·日期和时间表示法》与ISO 8601:1988等效
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
});
var app = angular.module('pftApp', ['multipleDatePicker']);
var selectedDates = [];
app.controller('pftController', ['$scope', function ($scope) {
    $scope.doDate = function (event, date) {
        var _date = moment(date).format('YYYY-MM-DD');

        if (!date.selectable) {
            PFT_GLOBAL.U.Alert("fail",'<p style="width:520px">【'+_date+'】已经设置过场次；如需添加场次您可以通过编辑场次链接添加场次</p>', 5000);
            return false;
        }
        if (event.type == 'click') {
//            console.log(date);
            if (!date.selected) {
                if(selectedDates.indexOf(_date) == -1) {
                    selectedDates.push(_date);
                }
            } else {
                selectedDates.splice(selectedDates.indexOf(_date), 1); //remove the date
            }
//            console.log(selectedDates);
        }
    };
    var day_list = function(){
        var arr = [];
        if (typeof global_selected_dates != 'undefined') {
            for(var i=0;i<global_selected_dates.length;i++) {
//            console.log(global_selected_dates[i]);
                arr.push(
                    {date: moment(global_selected_dates[i]).valueOf(), css: 'holiday', selectable: false,title: '已设置场次'}
                );
            }
        }
        return arr;
    };
    $scope.highlightDays = day_list();
//    $scope.highlightDays = [{date: moment('2015-06-22').valueOf(), css:'holiday', selectable: false,title: '已设置场次' }];
//    $scope.highlightDays = [
//        {date: moment().date(2).valueOf(), css: 'holiday', selectable: false,title: '已设置场次'}
//    ];
//    $scope.selectedDays = [moment().date(4).valueOf(), moment().date(5).valueOf(), moment().date(8).valueOf()];
}]);
jQuery(document).ready(function($){
    var inc = -1,
        key_index = $("input#key_index").length ? parseInt($("input#key_index").val()) :2;
    $("#round_body").on('click','a.rm',function(){
        //if(index==0) return;
        var round_id = $(this).attr('data-rid');
        if($(this).attr('data-edit')==1) {
            if(!confirm('该配置已保存，您确定要删除？')) {
                return;
            }
            $.post('call/jh_round.php',{rid:round_id,status:1, action:'SET_ROUND_STATE'},function(json){
                if(json.code=='200') {
                    $("tr#round_"+round_id).remove();
                    PFT_GLOBAL.U.Alert("success",'<p style="width:120px">删除成功</p>');
                } else {
                    alert('删除失败！');
                }
            }, 'json');
        } else {
            if(inc==0){
                return;
            }
            $("#round_"+round_id).remove();
            key_index -= 1;
        }
    });
    $(".btn-add").on('click',function(){
        if(key_index>20) {
            alert('一次性添加不能超出20个场馆！');
            return;
        }
        var content = $("#round_tpl").html();
        var newcontent = content.replace(/{k}/g,inc).replace(/{inc}/g,key_index);
        $("#round_body").append(newcontent);
        inc -= 1;
        key_index += 1;
    });
    var post_data = function(form_data, $btn, action){
        if (!form_data) return false;
        var action = action || 'SAVE_ROUND';
//        console.log(action);
        $.ajax({
            type:'post',
            data:form_data,
            dataType:'json',
            url:'call/jh_round.php?action=' + action,
            before: function(){
                $btn.attr('disable','disable');
            },
            success: function(json){
                $btn.removeAttr('disable');
                if (json.code=='200') {
//                    console.log(json);
                    PFT_GLOBAL.U.Alert("success",'<p style="width:120px">操作成功</p>');
                } else {
                    PFT_GLOBAL.U.Alert("fail",'<p style="width:520px">'+json.msg+'</p>', 5000);
                }
            }
        });
    };
    var verify_data = function(){
        var inputs = $("form").find('input');
        for (var i=0;i<inputs.length;i++) {
            var elem = $(inputs[i]),_val = elem.val();
            if (_val=='') {
                alert(elem.data('title')+'不能为空');
                elem.focus();
                return false;
            }
            if (elem.attr('type')=='number') {
                if (isNaN(_val)) {
                    alert(elem.data('title')+'必须为数字格式');
                    elem.focus();
                    return false;
                } else if( _val < 0) {
                    alert(elem.data('title')+'必须大于0');
                    elem.focus();
                    return false;
                }
            } else if(elem.attr('type')=='time') {
                if (_val.indexOf(':')>-1) {
                    var time = _val.split(':'),
                        bt   = time[0],
                        et   = time[1];
                    if (isNaN(bt) || isNaN(et)) {
                        alert(elem.data('title')+'必须为数字格式');
                        elem.focus();
                        return false;
                    }
                    else if(bt>23 || et> 59 || bt<0 || et<0) {
                        alert(elem.data('title')+'格式错误');
                        elem.focus();
                        return false;
                    }
                } else {
                    alert('时间格式错误');
                    elem.focus();
                    return false;
                }
            }
        }
        return true;
    };
    $(".save-btn").on('click', function(){
        if (selectedDates.length==0) {
            alert('请选择日期');
            return false;
        }
        if (!verify_data()) {
            return false;
        }
        var form_data = $("#round_form").serialize(),
            dates = selectedDates.join(',');
        post_data(form_data+'&dates='+selectedDates, $(this));
    });
    //更新
    $(".update-btn").on('click', function(){
        if (verify_data()==false) {
            return false;
        }
        post_data($("#round_form").serialize(), $(this));
    });
    //同步
    $(".sync-btn").on('click', function(){
        var form_data = $("#round_form").serialize(),
            dates = selectedDates.join(',');
        post_data(form_data+'&dates='+selectedDates, $(this), 'SYNC_ROUND');
    });
    //场次列表-时间变更提交查询
    $("input[name=bt]").on('change', function(){
        $("#search-form").submit();
    });
    //场次列表-取消场次
    $(".round-list-tbl").on('click','a.cancel-round', function(){
        console.log($(this).data('id'));
        if (!confirm('您确定要取消该场次吗？')) return false;
        var rid = $(this).data('id');
        post_data({id:rid, status:1}, $(this), 'CANCEL_ROUND');
    });
});

